package com.ssm.util;

import com.ssm.service.TeacherService;
import com.ssm.service.impl.TeacherServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Lenovo on 2019/11/8.
 */
public class ProxyFactory {
    final static  TeacherServiceImpl teacherService=new TeacherServiceImpl();
    final static MyAspect ma=new MyAspect();
    public static TeacherServiceImpl CreateProxy(){
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(teacherService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                  ma.before();
                  Object obj=method.invoke(teacherService,args);
                  methodProxy.invokeSuper(proxy,args);
                  ma.after();
                  return  obj;
            }
        });
        return (TeacherServiceImpl)enhancer.create();
    }
}
